package api

import (
	validatorV10 "github.com/go-playground/validator/v10"
	"reflect"
	"sync"
)

func validate(t interface{}) error {
	return defaultValidator.ValidateStruct(t)
}

var defaultValidator = &Validator{}

type Validator struct {
	once     sync.Once
	validate *validatorV10.Validate
}

func (v *Validator) ValidateStruct(obj interface{}) error {
	value := reflect.ValueOf(obj)
	valueType := value.Kind()
	if valueType == reflect.Ptr {
		valueType = value.Elem().Kind()
	}
	if valueType == reflect.Struct {
		v.lazyInit()
		if err := v.validate.Struct(obj); err != nil {
			return err
		}
	}
	return nil
}

func (v *Validator) lazyInit() {
	v.once.Do(func() {
		v.validate = validatorV10.New()
		v.validate.SetTagName("binding")
	})
}
